import pandas as pd
from collections import defaultdict
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
df=pd.read_csv('new_data.csv',encoding='gbk')
data1=[]
for i in df.values:
    data1.append([i[1],i[2],i[3],i[4],i[5],i[6],i[7],i[8]])

# 模拟数据
data = data1
columns = ['index', '用户id', '性别', '点赞数', '评论', '回复量', '评论日期', '哪吒关键词出现次数']
df = pd.DataFrame(data, columns=columns)

# 协同过滤推荐
def collaborative_filtering(user_id, n_rec=5):
    user_comments = defaultdict(list)
    for index, row in df.iterrows():
        user_comments[row['用户id']].append(row['评论'])

    user_comment_matrix = pd.DataFrame.from_dict(user_comments, orient='index').T.fillna('')

    vectorizer = TfidfVectorizer()
    comment_vectors = vectorizer.fit_transform(user_comment_matrix.values.flatten())
    comment_vectors = comment_vectors.reshape(len(user_comment_matrix), -1)

    cosine_sim = cosine_similarity(comment_vectors)

    user_index = list(user_comments.keys()).index(user_id)
    sim_scores = list(enumerate(cosine_sim[user_index]))
    sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
    sim_scores = sim_scores[1:]  # 排除用户自己

    similar_users = [list(user_comments.keys())[i[0]] for i in sim_scores[:n_rec]]

    rec_videos = []
    for similar_user in similar_users:
        user_df = df[df['用户id'] == similar_user]
        rec_videos.extend(user_df['评论'].tolist())

    return rec_videos[:n_rec]

# 基于内容的推荐
def content_based_recommendation(user_id, n_rec=5):
    user_comment = df[df['用户id'] == user_id]['评论'].values[0]

    all_comments = df['评论'].tolist()
    all_comments.append(user_comment)

    vectorizer = TfidfVectorizer()
    comment_vectors = vectorizer.fit_transform(all_comments)

    user_vector = comment_vectors[-1]
    other_vectors = comment_vectors[:-1]

    cosine_sim = cosine_similarity(user_vector, other_vectors).flatten()
    sim_scores = list(enumerate(cosine_sim))
    sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
    sim_scores = sim_scores[1:]  # 排除用户自己的评论

    rec_videos = [all_comments[i[0]] for i in sim_scores[:n_rec]]

    return rec_videos

# 混合推荐
def hybrid_recommendation(user_id, n_rec=5):
    cf_rec = collaborative_filtering(user_id, n_rec)
    cb_rec = content_based_recommendation(user_id, n_rec)

    rec_videos = list(set(cf_rec + cb_rec))[:n_rec]
    return rec_videos

# 测试
user_id = 256449071441
print(f"协同过滤推荐结果: {collaborative_filtering(user_id)}")
print(f"基于内容的推荐结果: {content_based_recommendation(user_id)}")
print(f"混合推荐结果: {hybrid_recommendation(user_id)}")